package user.Controller.searchBook;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import user.utils.DBUitls;
import user.utils.JsonUntil;
import user.Model.entity.book;
import user.Model.service.Service;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
/*
* 获取搜索的信息
* 返回搜索的书籍的集合
* */
@WebServlet(name = "searchBookServlet",urlPatterns = "/user/searchBookServlet")
public class searchBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转化成String类
        String jsonString=String.valueOf(JsonUntil.getJson(req));
        //转换成JSONObject类
        JSONObject jsonObject= JSON.parseObject(jsonString);
        //获取搜索值
        String bookInformation = jsonObject.getString("bookInformation");
        //获取搜索到的书籍集合
        ArrayList<book> books = new ArrayList<>();
        try {
            books = Service.searchBook(bookInformation);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                DBUitls.freeConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //向前端输出数据
        PrintWriter out = resp.getWriter();
        JSONObject object = new JSONObject();
        //如果该集合为空
        if (books.isEmpty()){
            object.put("code","-1");
            object.put("message","您要查询的该书籍信息不存在");
            out.println(object);
        }
        else{
            //序列化该集合
            String bookList = JSONObject.toJSONString(books);
            object.put("books",bookList);
            object.put("code","200");
            object.put("message","查询成功");
            object.put("userType","user");
            out.println(object);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
